﻿using DDNS.Infrastructure;
using DDNS_IPv4_IPv6.Interface;

namespace DDNS_IPv4_IPv6.Service
{
    /// <summary>
    /// 执行定时任务
    /// </summary>
    public class TimeJobService : BackgroundService
    {
        private readonly int _spendMilliSeconds = 5000;//毫秒数(执行频率)
        private readonly IDynamicParsingService _dynamicParsingService;
        private readonly ILogger<TimeJobService> _logger;
        public TimeJobService(IDynamicParsingService dynamicParsingService, ILogger<TimeJobService> logger)
        {
            _dynamicParsingService = dynamicParsingService;
            _spendMilliSeconds = PassportConfig.GetInt("MilliSeconds") == 0 ? 5000 : PassportConfig.GetInt("MilliSeconds");
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    _dynamicParsingService.SetDDNS_IPv4();
                    _dynamicParsingService.SetDDNS_IPv6();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"执行定时任务异常：{ex.Message}");
                }
                await Task.Delay(_spendMilliSeconds, stoppingToken);
            }
        }

        //public override async Task StopAsync(CancellationToken stoppingToken)
        //{
        //    await Task.Delay(1, stoppingToken);
        //}
    }
}
